package util;

import server.HttpServlet;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class StandardClassLoader extends ClassLoader {


        public static void main(String[] args){
            StandardClassLoader classLoader = new StandardClassLoader("E:/javaProPrograme/Session2/Session1-tomcat-nginx/Minicat/webapps/baidu");
            try{
                Class c = classLoader.loadClass("server.BaiduServlet");
                String simpleName = c.getSimpleName();
                Object object = c.getDeclaredConstructor().newInstance();
                HttpServlet servlet = (HttpServlet)object;
            }catch (Exception e){
                e.printStackTrace();
            }
        }


        private String mLibPath;




        public StandardClassLoader(String path) {
            // TODO Auto-generated constructor stub
            mLibPath = path;
        }

        @Override
        protected Class<?> findClass(String name) throws ClassNotFoundException {
            // TODO Auto-generated method stub

            String fileName = mLibPath + "/"+name.replaceAll("\\.","/")+".class";

            File file = new File(fileName);

            System.out.println(fileName);
            try {
                FileInputStream is = new FileInputStream(file);

                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                int len = 0;
                try {
                    while ((len = is.read()) != -1) {
                        bos.write(len);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                byte[] data = bos.toByteArray();
                is.close();
                bos.close();

                return defineClass(name,data,0,data.length);

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return super.findClass(name);
        }

        //获取要加载 的class文件名
        private String getFileName(String name) {
            // TODO Auto-generated method stub
            int index = name.lastIndexOf('.');
            if(index == -1){
                return name+".class";
            }else{
                return name.substring(index+1)+".class";
            }
        }


}
